<template>
  <vue-content>
    <vue-header>
      <vue-header-form>
        <el-form :inline="true" :model="formFilter" ref="formFilter">
          <el-form-item label="员工积分信息导入模板">
            <el-button size="small" type="info" @click="integraldownload">下载模板</el-button>
          </el-form-item>
          <el-form-item label="上传员工积分信息excel">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="baseUrl()"
              :auto-upload = "false"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :before-remove="beforeRemove"
              :on-exceed="handleExceed"
              accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              multiple
              :limit="1"
              :file-list="fileList">
              <el-button type="info">选择导入文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="info" :disabled="importSubabled" @click="Submit('formFilter')">导入</el-button>
          </el-form-item>
        </el-form>
      </vue-header-form>
      <div style="float:right">
          <el-button type="info" @click="batchImportIntegral()">员工积分信息导入列表</el-button>
          <el-button type="info" @click="back()">后退</el-button>
      </div>
    </vue-header>
    <vue-body>
      <el-table
        v-loading.body="loading"
        :data="tableData"
        v-if="tableData != ''"
        border
        style="width: 100%">
        <el-table-column label="批量导入错误信息表">
        <el-table-column
          prop="name"
          width="150"
          label="员工姓名">
        </el-table-column>
        <el-table-column
          prop="staffNo"
          label="工号">
        </el-table-column>
        <el-table-column
          prop="integral"
          label="导入积分">
        </el-table-column>
        <el-table-column
          prop="errorReason"
          label="错误原因">
        </el-table-column>
        </el-table-column>
      </el-table>
      <br />
      <el-table
        v-loading.body="loading"
        :data="rightTableData"
        v-if="rightTableData != ''"
        border
        style="width: 100%">
        <el-table-column label="已成功导入积分信息表">
        <el-table-column
          prop="name"
          width="150"
          label="员工姓名">
        </el-table-column>
        <el-table-column
          prop="staffNo"
          label="工号">
        </el-table-column>
        <el-table-column
          prop="integral"
          label="导入积分">
        </el-table-column>
        </el-table-column>
      </el-table>
    </vue-body>
    <vue-footer v-if="rightTableData != ''" style="padding: 5px 0;margin: 0 -5px;float:right;">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="pageSize">
      </el-pagination>
    </vue-footer>
    <br/>
    <vue-header-button>
      <el-button type="info" v-if="formFilter.applyNo != ''" :disabled="Subabled" @click="stopSubmit()">取消导入</el-button>
      <el-button type="info" v-if="formFilter.applyNo != ''" :disabled="Subabled" @click="finalySubmit()">提 交</el-button>
    </vue-header-button>
    <br/>
  </vue-content>
</template>
<script>
  import { md5 } from '@/utilities/crypto' // 加密
  import AuthStorage from '@/services/storage.js'
  import {confirmImportIntegral,queryImportIntegral,cancelImport} from '@/services/batchImport'
  import { oneFile } from "@/services/getFromData";
  import {queryStaffApply} from '@/services/batchImport'
  import {RequestError} from '@/services/errors'
  import {deepClone} from '@/utilities/object'
  export default {
    name: 'comp-table',
    components: {},
    data: () => ({
      loading: false,
      currentPage: 1,
      pageSize: 10,
      rightTableData:[],
      tableData: [],
      file:{},
      fileList:[],
      Subabled:false,
      importSubabled:false,
      currentPage: 1,
      pageSize: 10,
      formFilter: {
        companyNo: "",
        applyNo:""
      },
      loading: false,
      view: '',
      applyNo:"",
      downExcel: {
        fileType: "02"
      }
    }),
    created () {
      // 取到路由带过来的参数 
      let routerParams = this.$route.query;
      // 将数据放在当前组件的数据内
      this.formFilter.companyNo = routerParams.companyNo;
    },
    computed: {
    },
    methods: {
      async loadData () {
        this.loading = true
        try {
          let data = await queryImportIntegral(Object.assign({currentPage: this.currentPage},{perPage:10}, this.formFilter))
          // debugger
          this.rightTableData = data.data
          this.pageSize = parseInt(data.totalResult)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
        this.loading = false
      },
      baseUrl(){
        return "";
      },
      handleRemove(file, fileList) {
        this.importSubabled = false;
        this.file = "";
      },
      handleChange(file,fileList){
        this.importSubabled = false;
        this.file = file.raw;
        this.regExcel(file);
        this.regMemory(file);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制只能导入 1 个文件`);
      },
      regMemory(file){
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$refs.upload.clearFiles();
          this.file = ""
          this.$message.error('上传Excel文档大小不能超过 10MB!');
        }
      },
      regExcel(file){
        var path = file.raw.name;  //得到的是现在文件的路径
        var Suffix = path.substr(path.lastIndexOf(".")).toUpperCase();//得到的是后缀名,且转换为大写
        // console.log(Suffix)
        if(Suffix != ".XLS" && Suffix !=".XLSX"){
          this.$refs.upload.clearFiles();
          this.file = ""
          this.$message.error('只能上传后缀为.xls或.xlsx的Excel文档!');
        }
      },
      integraldownload(){
        this.exportData();
      },
      async exportData(){
        // 下载导入Excel模板
        var param=Object.assign(this.downExcel);
        var  a = new Date();
        var btime= a .getTime();
        var signs2 = "data="+JSON.stringify(param)+"&stmb="+btime;
        this.postDownLoadFile({
          url: this.$store.state.exportUrl + 'ecshop/template/downloadTemplateFile.do?stmb='+ a.getTime() +'&source="03"&token='+ AuthStorage.token +'&version=""&data='+JSON.stringify(param)+'&sign='+this.signature(signs2),
          method:'post'
        });
      },
      signature(data) {
        return md5(data)
      },
      postDownLoadFile(options) {
          var config = $.extend(true, { method: 'post' }, options);
          var $iframe = $('<iframe id="down-file-iframe" />');
          var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
          $form.attr('action', config.url);
          for (var key in config.data) {
              $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
          }
          $iframe.append($form);
          $(document.body).append($iframe);
          $form[0].submit();
          $iframe.remove();
      },
      batchImportIntegral(){
        this.$router.push({
	        path: 'staffManager/batchImportIntegral',
	        name: 'batchImportIntegral',
	        query: { 
            companyNo: this.formFilter.companyNo
          }
        })
      },
      back(){
        this.$router.go(-1)
      },
      Submit(formName) {
        this.importSubabled = true;
        // this.butTimeOut();
        this.$refs[formName].validate(async valid => {
          if (valid) {
            try {
                var sref = this;
                //把图片的信息和参数放进请求头里
                let code = await oneFile({
                  companyNo:this.formFilter.companyNo
                },"/ecshop/staff/resolveStaffAccountExcelTemplate.do","file",sref.file).then(
                  function(data){
                    // sref.$message({
                    //   showClose: true,
                    //   message: "文件已导入",
                    //   type: "success"
                    // });
                    // console.log(data)
                    sref.tableData = data.data.errorList
                    sref.applyNo = data.data.applyNo;
                    sref.formFilter.applyNo = data.data.applyNo;
                    sref.loadData();
                  }, 
                  function(reason, data){
                    sref.$message({
                      showClose: true,
                      message: reason,
                      type: "error"
                    });
                  });
            } catch (e) {
              if (e instanceof RequestError) {
                this.$alert(e.message, "提示", {
                  type: "error",
                  confirmButtonText: "确定"
                });
              } else {
                throw e;
              }
            }
          } else {
            return;
          }
        });
      },
      async finalySubmit(){
        this.Subabled = true;
        this.butTimeOut();
        this.$confirm(`是否提交此次员工积分导入?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await confirmImportIntegral(this.formFilter.applyNo);
            this.$message({
              showClose: true,
              message: "提交成功",
              type: "success"
            });
            this.$router.push({
              path: 'staffManager', 
              name: 'staffManager',
              query: { 
                
              }
            })
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消此次提交'
          })
        })
      },
      async stopSubmit(){
        this.Subabled = true;
        this.butTimeOut();
        this.$confirm(`是否取消此次员工积分导入?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await cancelImport(this.formFilter.applyNo,this.formFilter.companyNo);
            this.$message({
              showClose: true,
              message: "已取消积分信息导入",
              type: "success"
            });
            this.$router.push({
              path: 'staffManager', 
              name: 'staffManager',
              query: { 
              }
            })
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已放弃此次操作'
          })
        })
      },
      butTimeOut(){
        var serf = this;
        setTimeout(function(){
          serf.Subabled = false;
        },1200)
      }
    },
    watch: {
      currentPage (newVal) {
        this.loadData(newVal)
      }
    },
    filters: {
      applyStatus (value) {
        return {"00": '删除',"01": '草稿', "02": '已提交', "03": '已审核', "04": '拒绝', "05": '已完成', "06": '已取消'}[value]
      }
    },
  }
</script>

<style>
	.logoImgPic{
		height: 100px;
		display: block;
	}
	.el-table th>.cell{
		text-align: center;
	}
</style>
